const http = require("http");
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const { getEnvironmentData } = require("worker_threads");
const { FORMERR } = require("dns");

let dataList = [];
http.createServer((req, res) => {
    //获取请求路径pathname
    let urlObj = new URL(req.url, "http://192.168.174.166:8080/")
    if (urlObj.pathname.indexOf("/static") >= 0) {
        staticSend(urlObj, res);
    } else if (urlObj.pathname.indexOf("/api") >= 0) {
        dataSend(urlObj, req, res);
    }
}).listen(8080);
console.log("server is listening 8080")

//获取静态资源
function staticSend(urlObj, res) {
    switch (urlObj.pathname) {
        case "/static":
            let filePath = path.join(__dirname, "todoList.html");
            let fileContent = fs.readFileSync(filePath);
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(fileContent);
            break;
    }
}

//数据处理接口
function dataSend(urlObj, req, res) {
    switch (urlObj.pathname) {
        case "/api/adddata":
            adddata(req, urlObj, res);
            break;
        case "/api/list":
            getData(req, urlObj, res);
            break;
        case "/api/del":
            delData(req, urlObj, res);
            break;
    }
}

//获取数据列表
function getData(req, urlObj, res) {
    let dataStr = JSON.stringify(dataList);
    res.end(dataStr);
}

//添加数据
function adddata(req, urlObj, res) {
    let str = ""
    req.on("data", (chunk) => {
        str += chunk;
    })
    req.on("end", () => {
        let dataObj = JSON.parse(str);
        dataObj.id = Math.random();
        dataList.push(dataObj);
        let statusMsg = { "status": "ok" };
        statusMsg = JSON.stringify(statusMsg);
        res.end(statusMsg);
    })
}

function delData(req, urlObj, res) {
    let str = "";
    req.on("data", (chunk) => {
        str += chunk;
    })
    req.on("end", () => {
        let obj = JSON.parse(str);
        let id = obj.id;
        for (let i = 0; i < dataList.length; i++) {
            if (id == dataList[i].id) {
                dataList.splice(i, 1);
                res.end(JSON.stringify({ status: "ok" }))
                break;
            }
        }
    })
}